package com.newtouch.bxzs.business.train.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.business.train.mapper.ExaminationPaperExaminationQuestionsMapMapper;
import com.newtouch.bxzs.business.train.mapper.ExaminationPaperMapper;
import com.newtouch.bxzs.business.train.model.bo.ExaminationPaperBaseInfoDetailBO;
import com.newtouch.bxzs.business.train.model.bo.ExaminationPaperForExaminationBO;
import com.newtouch.bxzs.business.train.model.bo.ExaminationPaperPCListBO;
import com.newtouch.bxzs.business.train.model.vo.ChangeExaminationPaperStateVO;
import com.newtouch.bxzs.business.train.model.vo.ExaminationPaperForExaminationListVO;
import com.newtouch.bxzs.business.train.model.vo.ExaminationPaperPCListVO;
import com.newtouch.bxzs.business.train.model.vo.ModifyExaminationPaperBaseInfoVO;
import com.newtouch.bxzs.business.train.service.ExaminationPaperService;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.em.PaperStatusEnum;
import com.newtouch.bxzs.common.base.model.ExaminationPaper;
import com.newtouch.bxzs.common.base.model.ExaminationPaperExaminationQuestionsMap;
import com.newtouch.bxzs.common.base.util.EntityToBeanUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;

/**
 * 考试试卷相关业务逻辑
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/1/22</td>
 * <td>lanwei</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author lanwei
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class ExaminationPaperServiceImpl implements ExaminationPaperService {

    /**
     * 静态变量：系统日志
     */
    private static final Log logger = LogFactory.getLog(ExaminationPaperService.class);
    @Autowired
    private ExaminationPaperMapper examinationPaperMapper;
    @Autowired
    private ExaminationPaperExaminationQuestionsMapMapper examinationPaperExamiantionQuestionsMapMapper;
    @Override
    public IPage<ExaminationPaperForExaminationBO> getExaminationPaperForExamination(ExaminationPaperForExaminationListVO examinationPaperForExaminationListVO) {
        /*校验*/
		if (checkListPageParam(examinationPaperForExaminationListVO.getPageSize(),
				examinationPaperForExaminationListVO.getCurrentPage())) {
			logger.info("查询列表失败");
			throw new BaseException("-1", "传入数据有误");
		}
        String examinationId=examinationPaperForExaminationListVO.getExaminationId();
        Page<ExaminationPaperForExaminationBO> page = new Page<ExaminationPaperForExaminationBO>(examinationPaperForExaminationListVO.getCurrentPage(),examinationPaperForExaminationListVO.getPageSize());
        return examinationPaperMapper.getExaminationPaperForExamination(examinationId, page);
    }

    /**
     * 维护考试信息-查询试卷列表
     *
     * @param examinationPaperPCListVO
     * @return
     */
    @Override
    public IPage<ExaminationPaperPCListBO> getExaminationPaperPCList(ExaminationPaperPCListVO examinationPaperPCListVO) {
        /*校验*/
//        if (checkListPageParam(examinationPaperPCListVO.getPageSize(),examinationPaperPCListVO.getCurrentPage())) {
//            logger.info("查询列表失败");
//            throw new BaseException("-1", "传入数据有误");
//        }
        /*实例化一个QueryWrapper*/
        QueryWrapper<ExaminationPaper> query = new QueryWrapper<>();
        /* 考试名称 */
        if(!StringUtils.isEmpty(examinationPaperPCListVO.getExaminationPaperName())){
            query.like("EXAMINATION_PAPER_NAME", examinationPaperPCListVO.getExaminationPaperName());
        }
        /* 以题目创建时间降序排列 */
        query.orderByDesc("CREATE_TIME");
        Page<ExaminationPaper> p = new Page<>(examinationPaperPCListVO.getCurrentPage(), examinationPaperPCListVO.getPageSize());
        IPage<ExaminationPaper> examinationPaperPage = examinationPaperMapper.selectPage(p, query);
        if (examinationPaperPage == null) {
            return null;
        }
        IPage<ExaminationPaperPCListBO> page = new Page<>();
        /*将转换的BO放到advertisementBOList的Records*/
        page.setRecords(EntityToBeanUtils.copyBean(examinationPaperPage.getRecords(), ExaminationPaperPCListBO.class));
        page.setCurrent(examinationPaperPage.getCurrent());
        page.setPages(examinationPaperPage.getPages());
        page.setSize(examinationPaperPage.getSize());
        page.setTotal(examinationPaperPage.getTotal());
        return page;
    }

    /**
     * 创建、修改试卷基本信息
     *
     * @param examinationPaperBaseInfoVO
     * @return
     */
    @Override
    public String modifyExaminationPaperBaseInfo(ModifyExaminationPaperBaseInfoVO examinationPaperBaseInfoVO) {
        /*判断传入数据是否合格*/
        if (examinationPaperBaseInfoVO == null) {
            logger.info("新增或修改失败");
            throw new BaseException("-1", "传入数据有误");
        }
        /* 校验必传参数*/
        if(StringUtils.isEmpty(examinationPaperBaseInfoVO.getExaminationPaperName()) || null==examinationPaperBaseInfoVO.getExaminationQuestionsNumber()
                 || null==examinationPaperBaseInfoVO.getExaminationPaperStatus()){
            logger.info("新增或修改失败");
            throw new BaseException("-1", "有必填项未填！");
        }
        ExaminationPaper examinationPaper=new ExaminationPaper();
        /* 使用工具直接进行实体与BO的复制转换，注意字段名及类型需保持一致 */
        BeanUtil.copyProperties(examinationPaperBaseInfoVO, examinationPaper);

        if (StringUtils.isEmpty(examinationPaperBaseInfoVO.getExaminationPaperId())) {
            //新增试卷
            logger.info("新增试卷基本信息");
            examinationPaper.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            examinationPaper.setCreateTime(new Date());
            examinationPaper.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            examinationPaper.setUpdateTime(new Date());
            examinationPaper.setIsDelete(false);
            examinationPaperMapper.insert(examinationPaper);
            
            if(examinationPaperBaseInfoVO.getExaminationQuestionsIds()!=null&&examinationPaperBaseInfoVO.getExaminationQuestionsIds().size()>0){
            	modifyExaminationPaperExaminationQuestionsMap(examinationPaper.getExaminationPaperId(), examinationPaperBaseInfoVO.getExaminationQuestionsIds());
            }
        } else {
            //修改
            logger.info("修改试卷基本信息");
            examinationPaper.setUpdateUserId(Objects.requireNonNull(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId()));
            examinationPaper.setUpdateTime(new Date());
            examinationPaperMapper.updateById(examinationPaper);
            
            if(examinationPaperBaseInfoVO.getExaminationQuestionsIds()!=null&&examinationPaperBaseInfoVO.getExaminationQuestionsIds().size()>0){
            	modifyExaminationPaperExaminationQuestionsMap(examinationPaper.getExaminationPaperId(), examinationPaperBaseInfoVO.getExaminationQuestionsIds());
            }
        }
        return examinationPaper.getExaminationPaperId();
    }

    /**
     * 启用、禁用、作废试卷
     *
     * @param examinationPaperStateVO
     */
    @Override
    public Integer changeExaminationPaperState(ChangeExaminationPaperStateVO examinationPaperStateVO) {
        /*校验*/
        if (examinationPaperStateVO == null || StringUtils.isEmpty(examinationPaperStateVO.getExaminationPaperId())
                || (!Objects.equals(examinationPaperStateVO.getExaminationPaperStatus(), PaperStatusEnum.ENABLE_STATUS.getCode())
                && !Objects.equals(examinationPaperStateVO.getExaminationPaperStatus(),PaperStatusEnum.DISABLE_STATUS.getCode())
                &&!Objects.equals(examinationPaperStateVO.getExaminationPaperStatus(),PaperStatusEnum.INVALID_STATUS.getCode()))) {
            logger.info("修改状态失败");
            throw new BaseException("-1", "传入数据有误");
        }
        ExaminationPaper examinationPaper = examinationPaperMapper.selectById(examinationPaperStateVO.getExaminationPaperId());
        if(BeanUtil.isEmpty(examinationPaper)){
            logger.info("id不正确");
            throw new BaseException("-1", "id不正确");
        }
        if(Objects.equals(examinationPaperStateVO.getExaminationPaperStatus(),PaperStatusEnum.ENABLE_STATUS.getCode())
                && examinationPaperStateVO.getExaminationPaperStatus().equals(examinationPaper.getExaminationPaperStatus())){
            logger.info("修改状态失败");
            throw new BaseException("-1", "传入的考试已经处于启用状态");
        }else if(Objects.equals(examinationPaperStateVO.getExaminationPaperStatus(),PaperStatusEnum.DISABLE_STATUS.getCode())
                && examinationPaperStateVO.getExaminationPaperStatus().equals(examinationPaper.getExaminationPaperStatus())){
            logger.info("修改状态失败");
            throw new BaseException("-1", "传入的考试已经处于禁用状态");
        }else if(Objects.equals(examinationPaperStateVO.getExaminationPaperStatus(),PaperStatusEnum.INVALID_STATUS.getCode())
                && examinationPaperStateVO.getExaminationPaperStatus().equals(examinationPaper.getExaminationPaperStatus())){
            logger.info("修改状态失败");
            throw new BaseException("-1", "传入的考试已经处于作废状态");
        }
        /* 设置启用状态*/
        examinationPaper.setExaminationPaperStatus(examinationPaperStateVO.getExaminationPaperStatus());
        /*设置修改时间和修改人*/
        examinationPaper.setUpdateTime(new Date());
        examinationPaper.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        return examinationPaperMapper.updateById(examinationPaper);
    }

    /**
     * 删除试卷
     *
     * @param examinationPaperIds 试卷id集合
     */
    @Override
    public Integer deleteExaminationPaper(List<String> examinationPaperIds) {
        /*校验*/
        if (CollectionUtil.isEmpty(examinationPaperIds)) {
            logger.info("删除失败");
            throw new BaseException("-1", "集合为空");
        }
        QueryWrapper<ExaminationPaper> query=new QueryWrapper<>();
        query.in("EXAMINATION_PAPER_ID", examinationPaperIds).eq("EXAMINATION_PAPER_STATUS", PaperStatusEnum.ENABLE_STATUS.getCode());
        List<ExaminationPaper> examinationList = examinationPaperMapper.selectList(query);
        /*判断集合内是否有发布状态的考试*/
        if (!CollectionUtil.isEmpty(examinationList)) {
            logger.info("删除失败");
            throw new BaseException("-1", "存在状态为已启用的考试");
        }
        /*批量逻辑删除产品*/
        return examinationPaperMapper.deleteBatchIds(examinationPaperIds);
    }

    /**
     * 试卷基本信息
     *
     * @param examinationPaperId
     * @return
     */
    @Override
    public ExaminationPaperBaseInfoDetailBO getExaminationPaperBaseInfo(String examinationPaperId) {
        /*校验*/
        if (StringUtils.isEmpty(examinationPaperId)) {
            logger.info("查看详情失败");
            throw new BaseException("-1", "id为空");
        }
        ExaminationPaper examinationPaper = examinationPaperMapper.selectById(examinationPaperId);
        if (examinationPaper == null) {
            return null;
        }
        ExaminationPaperBaseInfoDetailBO examinationPaperBaseInfoDetailBO = new ExaminationPaperBaseInfoDetailBO();
        /* 使用工具直接进行实体与BO的复制转换，注意字段名及类型需保持一致 */
        BeanUtil.copyProperties(examinationPaper, examinationPaperBaseInfoDetailBO);
        return examinationPaperBaseInfoDetailBO;
    }

	/** 
	 * 新建、更新试题试卷映射表的信息 
	 */  
    @Override
    public void modifyExaminationPaperExaminationQuestionsMap(String examinationPaperId,
        List<String> examinationQuestionIds) {
        if (examinationQuestionIds == null || examinationPaperId == null || examinationQuestionIds.size() <= 0) {
            throw new BaseException("-1", "传入数据有误");
        }

        if (CollectionUtil.isEmpty(examinationQuestionIds)) {
            logger.info("删除失败");
        }

        List<String> examinationPaperExaminationQuestionsMapIds =
            examinationPaperExamiantionQuestionsMapMapper.getExaminationPaperExaminationQuestionIds(examinationPaperId);
        /* 判断集合内是否有数据 */
        if (!CollectionUtil.isEmpty(examinationPaperExaminationQuestionsMapIds)) {
            /* 批量逻辑删除产品 */
            int affectRows = examinationPaperExamiantionQuestionsMapMapper
                .deleteBatchIds(examinationPaperExaminationQuestionsMapIds);
            logger.info("删除试卷试题对应关系" + affectRows + "个");
        }
        ExaminationPaperExaminationQuestionsMap examinationPaperExaminationQuestionsMap = null;
     
        for (String examinationQuestionId : examinationQuestionIds) {
            examinationPaperExaminationQuestionsMap = new ExaminationPaperExaminationQuestionsMap();
            examinationPaperExaminationQuestionsMap.setExaminationPaperId(examinationPaperId);
            examinationPaperExaminationQuestionsMap.setExaminationQuestionsId(examinationQuestionId);
            examinationPaperExaminationQuestionsMap.setCreateTime(new Date());
            examinationPaperExaminationQuestionsMap
                .setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            examinationPaperExamiantionQuestionsMapMapper.insert(examinationPaperExaminationQuestionsMap);
        }
    }

	
    /**
     * 校验分页参数
     * @param pageParam
     * @return
     */
    private boolean checkListPageParam(Integer pageSize,Integer currentPage){
        if (pageSize == null || currentPage == null ||
                StringUtils.isEmpty(pageSize) || StringUtils.isEmpty(currentPage)
                || currentPage<1) {
            return true;
        }
        return false;
    }
}
